import axios from 'axios'
import { message } from 'ant-design-vue'
import { getStore } from './mUtils'
import { logout } from '@/api/loginout'
import store from '../store/index.js'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // baseURL: 'http://192.168.1.66:8001/',
  timeout: 500000, // request timeout
  headers: {
    // 'Content-Security-Policy': 'upgrade-insecure-requests'
  }
})

service.interceptors.request.use(
  (config) => {

    let url = config.url
    if (config.method === 'get') {
      url.indexOf('?') === -1 ? config.url = url + '?timeStamp=' + (new Date().getTime()) : config.url = url + '&timeStamp=' + (new Date().getTime())
    }


    const token = getStore('zhpk-sessionId')
    token ? config.headers.Authorization = token : null
    // config.headers.Authorization='f9dd7259-043e-4e2a-8cc1-d50b4b3489e7'

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  (response) => {

    const res = response.data

    if (res.code != 200) {
      if (res.code == 403) {
        message.destroy()
        message.warning('会话失效，请重新登录。')

        logout({}).then((res) => {
          localStorage.clear()


          top.window.location =
            process.env.VUE_APP_CAS_URL + '/logout?service=' + encodeURIComponent(store.state.appPublicUrl)

        })
      } else {
        message.destroy()
        message.error(res.message)
        // console.log(res);
        return res
      }

      return Promise.reject('error')
    } else {
      // 

      return res
    }
  },
  (error) => {
    let mes = ''
    if (error.response.data.error) {
      mes = error.response.data.error
    } else mes = error.response.data.message
    console.log(error.response)

    return Promise.reject(error)
  }
)

export default service
